# coding:utf-8
import zlib

__author__ = 'lanzhi'

import hashlib
import time
import urllib
import urllib2
import StringIO
import gzip

# reload(sys)
# sys.setdefaultencoding('utf8')

appkey = '*'
# 生产
appsecret = '*'


# appsecret = 'test1498734279'

# uat
# appsecret = 'xxx'


def send_request(method, url, **args):
    headers = {'Content-Type': 'text/xml',
               'Connection': 'keep-alive'
               }
    data = {
        'appkey': appkey,
        'ts': int(time.time()),
        #  secret不要显示在地址栏中
        # 'appsecret': appsecret,
    }
    # 加密
    data.update(args)
    # 排序
    data_sort = urllib.urlencode(sorted(data.iteritems(), key=lambda d: d[0]))
    # print data_sort
    # MD5加密
    m2 = hashlib.md5()
    # m2.update(data_sort.lower() + appsecret)
    m2.update(data_sort + appsecret)
    sign = m2.hexdigest()
    # 完事

    # 把sign加进dict，进行urlencode编码
    data['sign'] = sign
    # data.pop('appsecret')
    print data
    params = urllib.urlencode(data)
    print url + '?' + params
    if method == 'get':
        url = url + '?' + params
        request = urllib2.Request(url, headers=headers)
    elif method == 'post':
        request = urllib2.Request(url, params, headers=headers)
    try:
        response = urllib2.urlopen(request)

        encode = response.headers.get('Content-Encoding')
        print encode
        if encode == 'gzip':
            compresseddata = response.read()
            compressedstream = StringIO.StringIO(compresseddata)
            gzipper = gzip.GzipFile(fileobj=compressedstream)
            data = gzipper.read()
        elif encode == 'deflate':
            compresseddata = response.read()
            data = zlib.decompress(compresseddata, -zlib.MAX_WBITS)
        else:
            data = response.read()
        return data

    except urllib2.URLError, e:
        print ('URLError：' + e.reason)
    except urllib2.HTTPError, e:
        print ('HTTPError：' + e.code)
    if e.reason == 'Not Found':
        Case = 'connect'
        print ([Case, 'Page Not Found!!'])
    else:
        print 'connect is OK ~!'


# uat 电影 33753,card 6455
# prod 有相关业务 24311, jp 25450,movie 10111
if __name__ == '__main__':
    print('-----------start----------------')
    url = 'http://api.bilibili.com/pgc/season/app/related/recommend'
    response = send_request('get', url, season_id=21728, ad_extra='',platform='',device="", mobi_app="android", build=5330001)
    # url = 'http://show.bilibili.com/api/ticket/sug/seasonV2'
    # response = send_request('get', url, season_id=25510, mid="123",buvid = 60000000 )@
    # url = 'http://api.bilibili.com/pgc/web/recommend/related/recommend'
    # url = 'http://show.bilibili.co/api/ticket/sug/season'
    # url = 'http://api.bilibili.co/x/internal/v1/audio/menus/by-season'
    # url = 'http://api.bilibili.com/pgc/season/play/recommend'
    # response = send_request('get', url, season_id=25510)
    # response = send_request('get', url, season_id=33751)
    # response = send_request('get', url, id=24311, pageNum=1, pageSize=3)
    # url = 'http://uat-manager.bilibili.co/pgc/admin/season/tag/add'
    # response = send_request('post', url, season_id=33353, tag_names="123,12333")
    # url = 'http://api.bilibili.co/x/internal/v2/tag/tags'
    # response = send_request('get', url, oid=26154, type=6)

    # url = 'http://api.bilibili.com/pgc/app/v2/page/bangumi/'
    # response = send_request('get', url, pgc_home_timeline_abtest="5", access_key="21ffd8e93a661bd4400f7550d7404021",
    #                         actionKey="appkey", device="phone", mobi_app="iphone", build=8400, platform="ios",
    #                         ts=1550568159)
    # print "response:" + response + "\n"
    # url = 'http://api.bilibili.com/pgc/app/v2/page/exchange'
    # response = send_request('get', url, access_key="21ffd8e93a661bd4400f7550d7404021",
    #                         actionKey="appkey", device="phone", mobi_app="iphone", build=8400, platform="ios",
    #                         oid=4171, type=2, ts=1550568159)

    # url = 'http://manager.bilibili.co/pgc/admin/season/data/order'
    # response = send_request('get', url, type=1, days="2019-04-11")
    #
    # url = 'https://api.bilibili.com/pgc/view/app/season'
    # ep_id = 96043
    # mobi_app = 'android'
    #
    # response = send_request(method='get', url='https://api.bilibili.com/pgc/view/app/season',
    #                         ep_id=ep_id, mobi_app=mobi_app)

    print "response:" + response + "\n"
    print "------finish--------------"
